<?php
declare (strict_types = 1);

namespace app\command;

use app\api\consDir\OrderPrefixConst;
use app\api\consDir\SandConst;
use app\api\services\AlipayService;
use app\api\services\SandService;
use app\common\models\Community\CommunityOrder;
use app\common\models\Order\OrderPay;
use think\console\Command;
use think\console\Input;
use think\console\input\Argument;
use think\console\input\Option;
use think\console\Output;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;
use think\facade\Log;

class CommunityOrderOpRefund extends Command
{
    protected function configure()
    {
        // 指令配置
        $this->setName('community:order:op:refund')
            ->setDescription('the community:order:op:refund command');
    }

    /**
     * @throws ModelNotFoundException
     * @throws DataNotFoundException
     * @throws DbException
     */
    protected function execute(Input $input, Output $output)
    {
        $where = [
            //['order_status','in',[1,4]],
            ['status','=',0],
            ['is_refund','=',0],
            ['expire_at','<=',date('Y-m-d H:i:s')],
            ['create_at','>=','2024-10-12']
        ];
        $list = OrderPay::getInstance()->where($where)->select();
        if(empty($list)){
            return false;
        }
        foreach($list as $v){
            try {
                //pay_status` tinyint(1) DEFAULT '1' COMMENT '1微信 2支付宝 3余额 4杉德'
                if ($v['payStatus'] == 2) {
                    $aliOrder = AlipayService::getInstance()->find($v['payNo']);
                    if (!empty($aliOrder) && $aliOrder['code'] == 10000) {
                        //退款 更新状态
                        $ret = AlipayService::getInstance()->refund($v['payNo'], $aliOrder['total_amount']);
                        if (!empty($ret) && $ret['code'] == 10000) {
                            $v->is_refund = 1;
                            $v->refund_time = date('Y-m-d H:i:s');
                        }
                    }
                } elseif ($v['payStatus'] == 4) {
                    $price = env('test.is_test') == 1 ? 0.01 : $v['payPrice'];
                    //平台社区
                    $ret = [];
                    //`order_status` 0线上商城单 1社区单 2签到单 3礼包单 4转让单 5供应链单 6线下订单 7话费单 8充值 9预约
                    if(in_array($v->order_status,[0,4,5,8,9])){
                        //杉德查询到消费订单
                        $orderQuery = SandService::getInstance()->orderQuery($v['payNo']);
                        if (isset($orderQuery['orderStatus']) && $orderQuery['orderStatus'] == 'success') {
                            $ret = SandService::getInstance()->orderRefund(getNo(OrderPrefixConst::RF), $v['payNo'], $price);
                        }
                    }elseif($v->order_status == 1){
                        //社区订单
                        $communityOrder = CommunityOrder::getInstance()->where('order_no',$v['orderNo'])->find();
                        if ($communityOrder['lastOrderId'] == 0 || $communityOrder['isEnough']) {
                            //平台
                            //杉德查询到消费订单
                            $orderQuery = SandService::getInstance()->orderQuery($v['payNo']);
                            if (isset($orderQuery['orderStatus']) && $orderQuery['orderStatus'] == 'success') {
                                $ret = SandService::getInstance()->orderRefund(getNo(OrderPrefixConst::RF), $v['payNo'], $price);
                            }
                        } else {
                            //转让的社区
                            $userId = CommunityOrder::getInstance()->where('id', $communityOrder['lastOrderId'])->value('user_id');
                            $ret = SandService::getInstance()->transferConfirm(getNo(OrderPrefixConst::TC), $v['payNo'], $price, 'cancel', SandConst::PREFIX . $userId);
                            Log::info('取消转账' . json_encode($ret, 256));
                        }
                    }

                    if (isset($ret['resultStatus']) && $ret['resultStatus'] == 'success') {
                        $v->is_refund = 1;
                        $v->refund_time = date('Y-m-d H:i:s');
                    }
                }
                //取消订单
                $v->update_at = date('Y-m-d H:i:s');
                $v->status = 2;
                $v->save();
            } catch (\Exception $e) {
                Log::error($v['orderNo'] . $e->getMessage());
            }
        }
        // 指令输出
        $output->writeln('community:order:op:refund');
    }
}
